<?php
declare(strict_types=1);
/**
 * 阿里云上传文件服务
 */
namespace Service\FileService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\Sysconfig;
use League\Flysystem\Filesystem;
use Xxtime\Flysystem\Aliyun\OssAdapter;
class AliyunOssFileService extends BaseService
{
    /**
     * 上传文件服务
     * @param string $file
     */
    public function uploadFile(array $config,string $file)
    {
        $config = Sysconfig::instance()->getConfigByEventsValue($config['oss_way']);
        if( empty($config) ) {
            return Normal::returnCode(Normal::FAIL,"上传三方配置文件不存在");
        }
        
        $aliyun = new OssAdapter([
            'accessId'       => $config['oss_key_id'],
            'accessSecret'   => $config['oss_key_secret'],
            'bucket'         => $config['oss_bucket'],
            'endpoint'       => $config['oss_endpoint'],
            'timeout'        => 3600,
            'connectTimeout' => 10,
            // 'isCName'        => false,
            // 'token'          => '',
        ]);
        
        try 
        {
            $pathinfo   = pathinfo($file);
            $stream     = fopen($file, 'r+');
            $basename   = "/fileUpload/".date("YmdHis").'-'.$pathinfo['basename'];
            $filesystem = new Filesystem($aliyun);
            $filesystem->writeStream($basename,$stream);
            if (is_resource($stream)) {
                fclose($stream);
            }
            return Normal::returnCode(Normal::SUC,"上传成功",[
                'url'   => $config['url'].$basename
            ]);
        } 
        catch ( \Throwable $th ) 
        {
            return Normal::returnCode(Normal::FAIL,"上传三方文件失败{$th->getMessage()}");
        }
    }
}